<template>
	<view id="post-content">
		<!-- 添加图片 -->
		<view class="img-box">			
			<view class="img-list"><!-- 图片列表 -->
				<view class="img-plus img" @click="addImage()">	<!-- 上传图片 -->
					<image lazy-load="true"  src="../../static/images/add-img.png" class="img-plus-img"></image>
				</view>
				<view class="img-plus img" @click="addVideo()">	<!-- 上传图片 -->
					<image lazy-load="true"  src="../../static/images/add-video.png" class="img-plus-img"></image>
				</view>
				<view class="img img-out" v-for="(item,key) in img_list" :key='key'>
					<image lazy-load="true"  :src="item" @click="showPreviewImg(item)" class="img"></image>
					<text class="close" @click="deleteImg(key)">×</text>
				</view>
				<view class="img img-out" v-if="video_src">
					<video :src="video_src" class="img"></video>
					<text class="close" @click="deleteVideo()">×</text>
				</view>
			</view>
		</view>
		<!-- 文章 -->
		<view class="article-content">
			<!-- 文章标题 -->
			<view class="article-title">
				<input type="text" v-model="titleVal"  class="title wx_put ft-bold" placeholder="请输入12个字左右的标题哦~">
			</view>
			<!-- 文章内容 -->
			<view class="article-text">
				<textarea v-model="textVal" class="text wx_put"  placeholder="添加正文" />
			</view>
		</view>
		<!-- 添加商品 -->
		<view class="add-goods">	
			<view class="text text2" @click="goTopic()">
				<image lazy-load="true" src="../../static/images/add-goods-2.png" class="ico"></image>
				<block v-if="!topic">参与话题</block>
				<block v-if="topic">#{{topic}}#</block>
				<image lazy-load="true" src="../../static/images/jiantou1.png" class="jiantou"></image>
			</view>
			<view class="text" @click="goGoodsSelect()">
				<image lazy-load="true" src="../../static/images/add-goods-1.png" class="ico"></image>
				添加商品，赚取佣金
				<image lazy-load="true" src="../../static/images/jiantou1.png" class="jiantou"></image>
			</view>
			<view class="add-goods-list">
				<view class="goods-added" v-for="(item,key) in goodsList" :key="key">
					<view class="img"><image lazy-load="true"  :src="item.thumbnail" mode="aspectFit" class="img"></image></view>
					<view class="goods-info">
						<view class="title">{{item.name}}</view>
						<view class="type"></view>
						<view class="price">￥{{item.price/100}}</view>
					</view>
					<view class="delete" @click="deleteGoods(item.id)">
						<image lazy-load="true"  src="../../static/images/goods-add-delete.png" class="delete"></image>
					</view>
				</view>
			</view>
		</view>	
		<!-- 提交 -->
		<cover-view  class="submit-btn">
			<button class="submit-btn" @click="submitData()">发布笔记</button>
		</cover-view>
		<view class="empty"></view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				topicList:[
					
				],
				inputVal:"",
				imgList:[],
				goodsList:[],
				titleVal:"",
				textVal:"",
				idList:[],
				img_list:[],
				put_show:false,
				is_post:false,
				topic:'',
				imageBaseUrl:'https://weizong.file.cxbyi.com/images/',
				video_src:''
			}
		},
		onShow() {
			var self = this;
			this.imgList=uni.getStorageSync("imgList") ? uni.getStorageSync("imgList") : [];
			this.img_list=uni.getStorageSync("imgList") ? uni.getStorageSync("imgList") : [];
			this.goodsList=uni.getStorageSync("good-list") ? uni.getStorageSync("good-list") : [];
			this.topic=uni.getStorageSync("topic") ? uni.getStorageSync("topic") : '';
			this.video_src=uni.getStorageSync("video_uri") ? uni.getStorageSync("video_uri") : '';
			this.titleVal=uni.getStorageSync("article-title");
			this.textVal=uni.getStorageSync("article-content");
			this.put_show = true;
			// #ifdef H5
			let share_time_line={
				title:self.$request.h5_share_name, // 分享标题
				link: self.$request.h5_share_url+'?page=index', // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
				imgUrl: self.$request.h5_img_url+'/static/images/logo.png', // 分享图标
			}
			let share_app_message={
				title: self.$request.h5_share_name, // 分享标题
				desc: '我发现了一个很不错的商城，买家具有超大实惠！', // 分享描述
				link: self.$request.h5_share_url+'?page=index', // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
				imgUrl: self.$request.h5_img_url+'/static/images/logo.png', // 分享图标
			}
			uni.setStorageSync('share_time_line',share_time_line);
			uni.setStorageSync('share_app_message',share_app_message);
			self.$request.wx_config()
			// #endif
		},
		onShareAppMessage(res) {
		    if (res.from === 'button') {
		      console.log(res.target)
		    }
		    return {
		      title: this.$request.share_title,
		      path: '/pages/index/index'
		    }
		  },
		methods: {
			//	添加主题
			goTopic(){
				uni.setStorageSync("article-title",this.titleVal);
				uni.setStorageSync("article-content",this.textVal);
				uni.setStorageSync("article-topic",this.topicList);
				uni.setStorageSync("topic",this.topic);
				uni.navigateTo({
				    url: '../add-topic/add-topic'
				});
				// if(this.topicList.length==3){
				// 	uni.showToast({
				// 		title:'话题太多了~',
				// 		icon:'none',
				// 		duration:1500
				// 	})
				// 	return false; 
				// }
				// if(!this.inputVal){
				// 	uni.showToast({
				// 		title:'请输入文字',
				// 		icon:'none',
				// 		duration:1500
				// 	})
				// 	return false; 
				// } 
				// var haskey=false;
				// this.topicList.forEach((item,index)=>{
				// 	if(item == this.inputVal){
				// 		uni.showToast({
				// 			title:'话题重复~',
				// 			icon:'none',
				// 			duration:1500
				// 		})
				// 		haskey = true;
				// 	}
				// })
				// if(!haskey){
				// 	this.topicList.push(this.inputVal);
				// 	this.inputVal='';
				// }
				
			},
			//	删除主题
			deleteTopic(val){
				var self = this;
				if(!val){
					return false;
				};
				var toppicIndex = self.topicList.indexOf(val);
				self.topicList.splice(toppicIndex,1)
			},
			//	删除商品
			deleteGoods(id){
				for(var i = 0; i < this.goodsList.length; i++){
					if(id == this.goodsList[i].id){
						var goodIndex = this.goodsList.indexOf(this.goodsList[i]);
						this.goodsList.splice(goodIndex,1);
						uni.setStorageSync("good-list",this.goodsList)
					}
				}
			},
			checkPublish(){
				if(this.imgList.length<1){
					uni.showToast({
					    title: '必须选择一张图片!',
					    duration: 2000,
							icon:"none"
					});
					return false;
				}
				if(this.goodsList.length<1){
					uni.showToast({
					    title: '必须选择至少一个商品!',
					    duration: 2000,
							icon:"none"
					});
					return false;
				}
				if(this.titleVal==""||this.textVal==""){
					uni.showToast({
					    title: '标题和内容都必须填写!',
					    duration: 2000,
							icon:"none"
					});
					return false;
				}
				return true;
			},
			//	预览
			preview(){
				uni.setStorageSync("article-title",this.titleVal);
				uni.setStorageSync("article-content",this.textVal);
				uni.setStorageSync("article-topic",this.topicList);
				this.checkPublish();
				if(this.checkPublish()){
					uni.navigateTo({
					    url: '../preview/preview'
					});
				}
				
			},
			showPreviewImg(url){
				uni.previewImage({
					urls:this.img_list,
					current:url
				})
			},
			//	添加图片
			addImage(){
				var self = this;
				uni.setStorageSync("article-title",this.titleVal);
				uni.setStorageSync("article-content",this.textVal);
				uni.setStorageSync("article-topic",this.topicList);
				uni.setStorageSync("topic",this.topic);
				if(this.imgList.length<5){
					var count = 5-this.imgList.length;
					uni.chooseImage({
						count:count,
					    success: (chooseImageRes) => {
							console.log(chooseImageRes)
					        const tempFilePaths = chooseImageRes.tempFilePaths;
							tempFilePaths.forEach((item,index)=>{
								uni.uploadFile({
								    url: self.$request.img_upload, //仅为示例，非真实的接口地址
								    filePath: item,
								    name: 'file',
								    formData: {
								        'user': 'test'
								    },
												header: {
													'factory-id': self.$request.factory_id,
													'token': uni.getStorageSync('token') || ""
												},
								    success: (uploadFileRes) => {
										console.log(uploadFileRes)
										if(JSON.parse(uploadFileRes.data).code==40003){
											uni.navigateTo({
												url:'../login/login?page=post'
											})
										}else if(JSON.parse(uploadFileRes.data).code==200){
											uni.showLoading({
											    title: '加载中'
											});
											setTimeout(function(){
												uni.hideLoading();
												var img_uri = JSON.parse(uploadFileRes.data).result[0].uri;
												
												if(img_uri){
													self.img_list.push(item);
													self.imgList.push(JSON.parse(uploadFileRes.data).result[0].uri);
													uni.setStorageSync("imgList",self.imgList);
													uni.setStorageSync("img_list",self.img_list);
												}else{
													uni.showToast({
													    title: JSON.parse(uploadFileRes.data).result[0].msg,
													    duration: 2000,
														icon:"none"
													});
												}
											},1000)
										}				
								    }
								});
							}); 
					    }
					});
					
					// #ifdef H5
					// self.wx.chooseImage({
					//   count: count, 
					//   sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
					//   sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
					//   success: function(res) {
					//     var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
					//     localIds.forEach(function(e) {
					//       self.wx.uploadImage({
					//         localId: e, // 需要上传的图片的本地ID，由chooseImage接口获得
					//         isShowProgressTips: 1, // 默认为1，显示进度提示
					//         success: function(res) {
					//           var serverId = res.serverId; 
					// 		  uni.showLoading({
					// 		      title: '请稍后~'
					// 		  });
					// 		  self.$request.request_config({
					// 		  	url:'/web/wechat/upload_image',
					// 		  	data:{
					// 				media_id: serverId,
					// 				},
					// 		  	success:function(res){
					// 		  		if (res.code == 200) {
					// 		  		  // let result = res.result
					// 		  		  // let url = self.imageBaseUrl + result[serverId]
					// 				  var img_uri = res.result[0].uri;
					// 				  if(img_uri){
					// 				  	setTimeout(function() {
					// 				  		uni.hideLoading();
					// 				  		self.img_list.push(img_uri);
					// 				  		self.imgList.push(img_uri);
					// 				  		uni.setStorageSync("imgList",self.imgList);
					// 				  		uni.setStorageSync("img_list",self.img_list);									 
					// 				  	}, 3000);
					// 				  }else{
					// 				  	uni.showToast({
					// 				  	    title: res.result[0].msg,
					// 				  	    duration: 2000,
					// 				  		icon:"none"
					// 				  	});
					// 				  }
					// 		  		}else{
					// 					uni.hideLoading();
					// 				}
					// 		  	}
					// 		  });
					//         }
					//       });
					//     });
					//   }
					// });
					// #endif
				}
				else{
					uni.showToast({
					    title: '最多只能上传五张图片',
							icon:"none",
					    duration: 2000
					});
				}
			},
			addVideo(){
				 var self = this; 
				 uni.setStorageSync("article-title",this.titleVal);
				 uni.setStorageSync("article-content",this.textVal);
				 uni.setStorageSync("article-topic",this.topicList);
				 uni.setStorageSync("topic",this.topic);
				// #ifdef MP-WEIXIN
				uni.chooseVideo({
					count:1,
					sourceType: ['camera', 'album'],
				    success: (res) => {
						console.log(res)
				        const src = res.tempFilePath;
						uni.uploadFile({
						    url: self.$request.video_upload, //仅为示例，非真实的接口地址
						    filePath: src,
						    name: 'video',
						    formData: {
						        'user': 'test'
						    },
							header: {
								'factory-id': self.$request.factory_id,
								'token': uni.getStorageSync('token') || ""
							},			
						    success: (uploadFileRes) => {
								console.log(uploadFileRes)
								if(JSON.parse(uploadFileRes.data).code==40003){
									uni.navigateTo({
										url:'../login/login?page=post'
									})
								}else if(JSON.parse(uploadFileRes.data).code==200){
									uni.showLoading({
									    title: '加载中'
									});
									setTimeout(function(){
										uni.hideLoading();
										var video_uri = JSON.parse(uploadFileRes.data).result[0].uri;
										
										if(video_uri){
											self.video_src=src;
											uni.setStorageSync("video_uri",video_uri);
										}else{
											uni.showToast({
											    title: JSON.parse(uploadFileRes.data).result[0].msg,
											    duration: 2000,
												icon:"none"
											});
										}
									},1000)
								}				
						    }
						});
				    }
				});
				// #endif		
				   
				   // #ifdef H5
					uni.chooseVideo({
						count:1,
						sourceType: ['camera', 'album'],
					    success: (res) => {
							console.log(res)
					        const src = res.tempFilePath;
							uni.uploadFile({
							    url: self.$request.video_upload, //仅为示例，非真实的接口地址
							    filePath: src,
							    name: 'video',
							    formData: {
							        'user': 'test',
									'header_factory_id':self.$request.factory_id,
									'header_token':uni.getStorageSync('token') || ""
							    },			
							    success: (uploadFileRes) => {
									console.log(uploadFileRes)
									uni.showLoading({
									    title: JSON.parse(uploadFileRes.data).code
									});
									if(JSON.parse(uploadFileRes.data).code==40003){
										uni.navigateTo({
											url:'../login/login?page=post'
										})
									}else if(JSON.parse(uploadFileRes.data).code==200){
										uni.showLoading({
										    title: '加载中'
										});
										setTimeout(function(){
											uni.hideLoading();
											var video_uri = JSON.parse(uploadFileRes.data).result[0].uri;
											
											if(video_uri){
												self.video_src=src;
												uni.setStorageSync("video_uri",video_uri);
											}else{
												uni.showToast({
												    title: JSON.parse(uploadFileRes.data).result[0].msg,
												    duration: 2000,
													icon:"none"
												});
											}
										},1000)
									}				
							    }
							});
					    },
						fail:(res)=>{
							
						}
					});
				   // #endif
			},
				
			deleteImg(key){
				this.imgList.splice(key,1);
				this.img_list.splice(key,1);
				uni.setStorageSync("imgList",this.imgList);
				uni.setStorageSync("img_list",this.img_list);
			},
			deleteVideo(){
				uni.setStorageSync("video_uri",'');
				this.video_src='';
			},
			goGoodsSelect(){
				uni.setStorageSync("article-title",this.titleVal);
				uni.setStorageSync("article-content",this.textVal);
				uni.setStorageSync("good-list","");
				uni.navigateTo({
				    url: '../goods-select/goods-select'
				});
			},
			//	提交数据
			submitData(){
				var self = this;
				
				if(!this.checkPublish()) return false;
				if(this.is_post) return;
				this.is_post = true;
				for(var i = 0;i<this.goodsList.length;i++){
					this.idList.push(this.goodsList[i].id);
				}
				self.$request.request({
					url:'/note/publish',
					data:{
						title:self.titleVal,
						content:self.textVal,
						images:self.imgList,
						store_sku_id:this.idList,
						topics:self.topic,
						video:uni.getStorageSync('video_uri')
					},
					success:function(res){
						if(res.code==200){
							console.log(res.result)
							uni.showToast({
							    title: '提交成功',
							    duration: 2000,
									icon:"none"
							});
							uni.setStorageSync("article-title",'');
							uni.setStorageSync("article-content",'');
							uni.setStorageSync("article-topic",'');
							uni.setStorageSync("imgList",'');
							uni.setStorageSync("img_list",'');
							uni.setStorageSync("good-list",'');
							uni.setStorageSync("video_uri",'');
							setTimeout(function(){
								uni.switchTab({
									url:'/pages/share/share'
								})
							},2000)
						}else if(res.code==40006){
							uni.showToast({
							    title: '标题或内容含有敏感词!',
							    duration: 2000,
									icon:"none"
							});
							var _title = res.result.title;
							var _content = res.result.content;
							if(_title.length>0){
								for(var a=0;a<_title.length;a++){
									self.titleVal=self.titleVal.replace(_title[a],"***")
								}
							}
							if(_content.length>0){
								for(var b=0;b<_content.length;b++){
									self.textVal=self.textVal.replace(_content[b],"***")
								}
							}
						}else if(res.code==40003){
							uni.navigateTo({
								url:'../login/login?page=post'
							})
						}
						
						if(res.code!==200){
							self.is_post = false;
						}
					}
				})
			}
		}
	}
</script>

<style>
	@import url("post.css");
</style>
